/**
 * 店铺授权弹框
 * author:elvis
 */

import React, { useState, useEffect, useMemo } from 'react';
import CommonModal from '@/components/CommonModal';
// import GlobalCatcherModal from './GlobalCatcherModal';
import AddOfflineStore from './AddOfflineStore';
import BuyConfirm from './BuyConfirm';
import AddQm from './AddQmModal';
import WphAuthorize from './WphAuthorize';
import AddJingdongStore from './AddJingdongStore';
import AddJuShuiTan from './AddJuShuiTan';
import AddTmallSupply from './AddTmallSupply';
import AddWhale from './AddWhale';
import AddVideoStore from './AddVideoStore';
import AddDeWu from './AddDeWu';
import AddWangDianTong from './AddWangDianTong';
import { Base64 } from 'js-base64';
import { message, Button } from 'antd';
import { find } from 'lodash';
import { commonColor } from '@/utils/config';
import { getCurrentUser } from '@/utils/authority';
import styles from './index.module.less';
import useSettingStore from "@/stores/setting";

let isJumpLogin;

const AuthorizeStore = ({ visible, shopPlatform, handleCancel }) => {
	const title = useSettingStore(state => state.title);

  const [id, setId] = useState(undefined); //当前选中的平台id
  const [visible1, setVisible] = useState(1);

  useEffect(() => {
    isJumpLogin = sessionStorage.getItem('mall_authorize_pdd');
    sessionStorage.setItem('mall_authorize_pdd', '');
  }, []);

  const baseData = [
    //天猫
    {
      id: 2,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/tianmao.png',
      name: '天猫',
      path: `https://oauth.taobao.com/authorize?response_type=code&client_id=23416550&redirect_uri=http://tb-api.zhaojiafang.com/TopSdk.php&state=${AUTHORIZE_URL}/taobao/callback-callback-`,
    },

    //京东
    {
      id: 3,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/jd.png',
      name: '京东',
      path: `https://auth.360buy.com/oauth/authorize?response_type=code&client_id=7400F31DF539216DBDA2E06BD5E91C57&redirect_uri=http://threegateway.zhaojiafang.com/jd/callback&state=`,
    },

    //拼多多，需要支持双应用授权，new_path是商城跳转过来携带授权参数时使用
    {
      id: 4,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/pdd2.png',
      name: '拼多多',
      path: `https://mms.pinduoduo.com/open.html?response_type=code&client_id=d151e0b2a81042d496d22f70a729a971&redirect_uri=https://www.zhaojiafang.com/pdd.php&state=${AUTHORIZE_URL}/pdd/callback-callback-`,
      new_path:
        'https://fuwu.pinduoduo.com/service-market/auth?response_type=code&client_id=4abd7d8b492c4f68aaa8bc5299dc32c3&redirect_uri=http://threegateway.zhaojiafang.com/pdd/oneClickLogin&state=',
    },

    //抖音
    {
      id: 14,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/dy.png',
      name: '抖音',
      path: `https://fuwu.jinritemai.com/authorize?service_id=1965&state=`,
    },

    //快手
    {
      id: 12,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/ks.png',
      name: '快手',
      path: `https://open.kwaixiaodian.com/oauth/authorize?appId=ks661466197236322196&redirect_uri=http://threegateway.zhaojiafang.com/ks/callback&scope=merchant_refund,merchant_item,merchant_order,user_info,merchant_user,merchant_logistics&response_type=code&state=`,
    },

    //唯品会
    {
      id: 13,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/wph.png',
      name: '唯品会',
      path: `https://auth.vip.com/oauth2/authorize?client_id=b24fa427&response_type=code&redirect_uri=http://threegateway.zhaojiafang.com/wph/callback&state=`,
    },

    //天猫供销
    {
      id: 21,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/tmgonxiao.png',
      name: '天猫供销',
    },

    //苏宁厂送
    {
      id: 22,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/suninziyin.png',
      name: '苏宁厂送',
      path: `https://open.suning.com/api/oauth/authorize?response_type=code&client_id=f5897586e032f84121dcc3e684d62ea2&redirect_uri=http://threegateway.zhaojiafang.com/sn_fd/callback&scope=item,price&itemcode=8547&state=`,
    },

    //1688
    {
      id: 5,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/albb.png',
      name: '阿里巴巴',
      path: `https://auth.1688.com/oauth/authorize?client_id=7342795&site=1688&redirect_uri=https://open-tb.zhaojiafang.com/alibaba.php&state=${AUTHORIZE_URL}/alibaba/callback--callback--`,
    },

    // 6: {
    //     src: 'https://imgniu.zhaojiafang.com/sn.png',
    //     src_w: 'https://imgniu.zhaojiafang.com/sn_w.png',
    //   },
    //   7: {
    //     src: 'https://imgniu.zhaojiafang.com/snlt.png',
    //     src_w: 'https://imgniu.zhaojiafang.com/snlt_w.png',
    //   },

    // { id: 6, src: imgData['6'].src, src_w: imgData['6'].src_w },
    // { id: 7, src: imgData['7'].src, src_w: imgData['7'].src_w },

    //京东云仓
    {
      id: 19,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/jdyc.png',
      name: '京东云仓',
      path: `https://oauth.jdl.cn/oauth/authorize?client_id=3d9625d4bc294e6db002351d6fcc6d86&redirect_uri=http://threegateway.zhaojiafang.com/jdLogistics/callback&response_type=code&state=`,
    },

    //淘工厂
    {
      id: 24,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/taobaFactory.png',
      name: ' 淘工厂',
      path: `https://auth.1688.com/oauth/authorize?client_id=6974920&site=c2m&redirect_uri=http://threegateway.zhaojiafang.com/alibaba_c2m/callback&state=`,
    },

    //好衣库
    {
      id: 23,
      src: 'https://imgniu.zhaojiafang.com/front-web%2FERP%2Fwhale.png',
      name: '好衣库',
    },

    //有赞
    {
      id: 8,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/youzan.png',
      name: '有赞',
      path:
        'https://diy.youzanyun.com/oauth/authorize?client_id=022d7ffa84e389e6cb&state=',
    },

    // 9: {
    //     src: 'https://imgniu.zhaojiafang.com/hqls.png',
    //     src_w: 'https://imgniu.zhaojiafang.com/hqls_w.png',
    //   },
    // { id: 9, src: imgData['9'].src, src_w: imgData['9'].src_w },

    //奇门
    {
      id: 11,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/qimen.png',
      name: '奇门',
    },

    //聚水潭
    {
      id: 20,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/jst.png',
      name: '聚水潭',
    },

    //线下店铺
    {
      id: 0,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/xianxia.png',
      name: '线下店铺',
    },

    //视频号小店
    {
      id: 25,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/videostore.png',
      name: '视频号小店',
    },

    //旺店通
    {
        id: 27,
        src: 'https://imgniu.zhaojiafang.com/front-web/ERP/wangdiantong.png',
        name: '旺店通',
      },
 
    //得物
    {
        id: 32,
        src: 'https://imgniu.zhaojiafang.com/front-web/ERP/deWu.jpg',
        name: '得物',
        path: 'https://open.dewu.com/#/authorize?response_type=code&redirect_uri=http://threegateway.zhaojiafang.com/deWu/callback&client_id=379edcc0af3d4335a1bbfe62ca8b4ba9&scope=all&state=',
      },    
    
     //小红书
     {
      id: 40,
      src: 'https://imgniu.zhaojiafang.com/front-web/ERP/red_book.png',
      name: '小红书',
      path: 'https://ark.xiaohongshu.com/ark/authorization?appId=6a92470a64fb4056afce&redirectUri=http://threegateway.zhaojiafang.com/redBook/callback&state=',
    },    
  ];

  const data = useMemo(()=>{
    if(shopPlatform == 'qimen'){
      return [
         //淘宝易发货
          {
            id: 26,
            src: 'https://imgniu.zhaojiafang.com/front-web/ERP/tb.png',
            name: '淘宝(易发货)',
            path: `https://oauth.taobao.com/authorize?response_type=code&client_id=23416550&redirect_uri=http://tb-api.zhaojiafang.com/TopSdk.php&state=${AUTHORIZE_URL}/taobao/callback-callback-`,
          }
      ]
    }else{
      return [
         //淘宝
        {
          id: 1,
          src: 'https://imgniu.zhaojiafang.com/front-web/ERP/tb.png',
          name: '淘宝',
          path: `https://oauth.taobao.com/authorize?response_type=code&client_id=23416550&redirect_uri=http://tb-api.zhaojiafang.com/TopSdk.php&state=${AUTHORIZE_URL}/taobao/callback-callback-`,
        },
        ...baseData
      ]
    }
  },[shopPlatform]) 

  //点击确定
  function handleOk() {
    if (id) {
      if (id == 11) {
        //奇门
        setVisible(4);
      } else if (id == '13') {
        setVisible(5);
      } else if (id == '19') {
        setVisible(6);
      } else if (id == '20') {
        setVisible('jushuitan');
      } else if (id == '21') {
        setVisible('tamll');
      } else if (id == '23') {
        setVisible('whale');
      } else if (id == '24') {
        const url = window.location.href;
        const obj = JSON.stringify({
          url,
          userName: getCurrentUser().account,
          uuid: getCurrentUser().uuid,
          josUrl: `http://${AUTHORIZE_URL}`,
        });
        const path = find(data, ['id', id]).path;
        const src = `${path}${encodeURIComponent(Base64.encode(obj))}`;
        window.location.href = src;
      } else if (id == '25') {
        setVisible('videoStore');
      } else if (id == 27) {
        setVisible('wangdiantong');
      }
       else if(id == '32'){
        setVisible('deWu');
      } else {
        setVisible(2);
      }
    } else {
      if (id == 0) {
        //线下店铺
        setVisible(3);
      } else {
        message.warning('请选择平台！');
      }
    }
  }

  //开始授权前信息处理
  const handleAuthorize = (val = {}) => {
    if (id == 4) {
      //拼多多
      const url = window.location.href;
      const pddObj = {
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        josUrl: `http://${AUTHORIZE_URL}`,
        pddSource: 1,
        ...val,
      };
      // 从商城过来的授权pdd的参数有区别，跟京东平台的参数类似，这里通过跳转过来设置的session做区分，进行参数兼容
      // if (isJumpLogin) {
      //   pddObj.josUrl = `http://${AUTHORIZE_URL}`;
      // }
      const obj = JSON.stringify(pddObj);
      const path = find(data, ['id', id]).new_path;
      const src = `${path}${Base64.encode(
        encodeURIComponent(obj)
      )}`;
      window.location.href = src;
    } else if ([1, 2, 5, 26].includes(id)) {
      //淘宝
      const url = window.location.href;
      const obj = {
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        ...val,
      };
      let path = find(data, ['id', id]).path;
      if (id == '26' || (id == '1' && title == '易发货')) {
        //淘宝商品在子域名为wmso
        obj.josUrl = `http://${AUTHORIZE_URL}`;
        path = `https://oauth.taobao.com/authorize?response_type=code&client_id=31991507&redirect_uri=http://threegateway.zhaojiafang.com/taobao/wms/callback&view=web&state=`;
      }
      const src = `${path}${encodeURIComponent(
        Base64.encode(JSON.stringify(obj))
      )}`;
      window.location.href = src;
    } else if ([3, 12, 13, 14, 32, 40].includes(id)) {
      //京东和快手,苏宁(22)
      const url = window.location.href;
      const obj = JSON.stringify({
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        josUrl: `http://${AUTHORIZE_URL}`,
        ...val,
      });
      const path = find(data, ['id', id]).path;
      const src = `${path}${Base64.encode(
        encodeURIComponent(obj)
      )}`;
      window.location.href = src;
    } else if (id == 22) {
      //苏宁厂送，淘工厂
      const url = window.location.href;
      const obj = JSON.stringify({
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        josUrl: `http://${AUTHORIZE_URL}`,
        ...val,
      });
      const path = find(data, ['id', id]).path;
      const src = `${path}${encodeURIComponent(Base64.encode(obj))}`;
      window.location.href = src;
    } else if (id == 8) {
      const url = window.location.href;
      const obj = JSON.stringify({
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        josUrl: `http://${AUTHORIZE_URL}`,
      });
      const path = find(data, ['id', id]).path;
      const src = `${path}${encodeURIComponent(
        encodeURIComponent(Base64.encode(obj))
      )}`;
      window.location.href = src;
    } else if (id == 19) {
      const url = window.location.href;
      const obj = JSON.stringify({
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        josUrl: `http://${AUTHORIZE_URL}`,
        ...val,
        spdFlag: 1,
      });
      const path = find(data, ['id', id]).path;
      const src = `${path}${encodeURIComponent(
        encodeURIComponent(Base64.encode(obj))
      )}`;
      // const src = `${path}${Base64.encode(obj)}`;
      window.location.href = src;
    }
  };

  // const GlobalCatcherModalProps = {
  //   visible: visible1,
  //   dispatch,
  //   handleVisible(val) {
  //     setVisible(val);
  //   }
  // }

  //应用服务购买确认框以及订单去往选项
  const BuyConfirmProps = {
    shopPlatform,
    isJumpLogin,
    id: id,
    visible: visible1 == 2,
    handleOk(val) {
      handleAuthorize(val);
    },
    handleCancel() {
      setVisible(1);
    },
  };

  //线下店铺弹框
  const AddOfflineStoreProps = {
    visible: visible1 == 3,
    handleVisible() {
      setVisible(1);
    },
  };

  //京东云仓
  const AddJingdongStoreProps = {
    visible: visible1 == 6,
    handleOk(val) {
      handleAuthorize(val);
    },
    handleVisible() {
      setVisible(1);
    },
  };

  //聚水潭
  const AddJuShuiTanProps = {
    visible: visible1 == 'jushuitan',
    handleOk(val) {
      handleAuthorize(val);
    },
    handleVisible() {
      setVisible(1);
    },
  };

  //得物
  const AddDeWuProps = {
    visible: visible1 == 'deWu',
    handleOk(val) {
      handleAuthorize(val);
    },
    handleVisible() {
      setVisible(1);
    },
  }

  const AddWhaleProps = {
    visible: visible1 == 'whale',
    handleVisible() {
      setVisible(1);
    },
  };

  //视频号小店弹窗
  const AddVideoStoreProps = {
    visible: visible1 == 'videoStore',
    handleVisible() {
      setVisible(1);
    },
  };

  //旺店通
  const AddWangDianTongProps = {
    visible: visible1 == 'wangdiantong',
    handleOk(val) {
        handleAuthorize(val);
    },
    handleVisible() {
        setVisible(1);
    },
  };

  const AddTmallSupplyProps = {
    visible: visible1 == 'tamll',
    handleOk(val) {
      handleAuthorize(val);
    },
    handleVisible() {
      setVisible(1);
    },
  };

  //奇门授权弹框
  const AddQmProps = {
    id: id,
    visible: visible1 == 4,
    handleVisible() {
      setVisible(1);
    },
  };

  //唯品会授权弹框
  const WphAuthorizeProps = {
    visible: visible1 == 5,
    handleOk(val) {
      handleAuthorize(val);
    },
    handleCancel() {
      setVisible(1);
    },
  };

  const onCancel = () => {
    handleCancel();
    setId(undefined);
    setVisible(1);
  };

  return (
    <>
      <CommonModal
        title="店铺授权"
        visible={visible}
        className={styles.shopModal}
        onCancel={onCancel}
        width="640px"
        noPadding={true}
        footer={[
          <Button className={styles.closeBtn} key="back" onClick={onCancel}>
            关闭
          </Button>,
          <Button
            className={styles.okBtn}
            key="save"
            type="primary"
            onClick={handleOk}
          >
            确认
          </Button>,
        ]}
      >
        <div className={styles.secTitle}>选择平台</div>
        <div className={styles.wrap}>
          {data.map((item) => {
            return (
              <div
                key={item.id}
                className={styles.contentBox}
                onClick={() => setId(item.id)}
                style={{
                  background: id == item.id ? '#F4F7FF' : '#fff',
                }}
              >
                <div className={styles.contentImg}>
                  <img src={item.src} />
                </div>
                <div className={styles.contenttext}>{item?.name}</div>
              </div>
            );
          })}
        </div>
        {/* <GlobalCatcherModal { ...GlobalCatcherModalProps } /> */}
      </CommonModal>
      <AddJingdongStore {...AddJingdongStoreProps} />
      <AddOfflineStore {...AddOfflineStoreProps} />
      <AddJuShuiTan {...AddJuShuiTanProps} />
      <AddTmallSupply {...AddTmallSupplyProps} />
      <BuyConfirm {...BuyConfirmProps} />
      <AddQm {...AddQmProps} />
      <AddWhale {...AddWhaleProps} />
      <AddVideoStore {...AddVideoStoreProps} />
      <WphAuthorize {...WphAuthorizeProps} />
      <AddDeWu {...AddDeWuProps} />
      <AddWangDianTong {...AddWangDianTongProps} />
    </>
  );
};

export default AuthorizeStore;
